<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item
        label="状态"
        label-width="150px"
        prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable>
          <el-option
            v-for="dict in product_spu_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['product:productSpu:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:productSpu:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:productSpu:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['product:productSpu:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="productSpuList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="SPU ID" align="center" prop="id" />
      <el-table-column label="商品分类" align="center" prop="categoryId" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="副标题/促销语" align="center" prop="subTitle" />
      <el-table-column
        label="商品描述"
        width="190"
        align="center"
        prop="description">
        <template #default="scope">
          <el-tooltip
            :content="scope.row.description"
            placement="top"
            v-if="scope.row.description && scope.row.description.length > 20">
            <span>{{ scope.row.description.substring(0, 20) }}...</span>
          </el-tooltip>
          <span v-else>{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="status">
        <template #default="scope">
          <dict-tag :options="product_spu_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updatedAt"
        width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        width="220"
        align="center"
        class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleDetail(scope.row)"
            >详情</el-button
          >

          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:productSpu:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:productSpu:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品SPU对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="productSpuRef"
        :model="form"
        :rules="rules"
        label-width="80px">
        <el-form-item label-width="100px" label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label-width="100px" label="副标题/促销语" prop="subTitle">
          <el-input v-model="form.subTitle" placeholder="请输入副标题/促销语" />
        </el-form-item>
        <el-form-item label-width="100px" label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label-width="100px" label="状态" prop="status">
          <el-select
            v-model="form.status"
            placeholder="请选择状态">
            <el-option
              v-for="dict in product_spu_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" label-width="100px" prop="categoryId">
          <el-tree-select
            v-model="form.categoryId"
            :data="productCategoryOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择商品分类"
            check-strictly />
        </el-form-item>
        <el-form-item label="规格模板" label-width="100px" prop="templateId">
          <el-select
            v-model="form.templateId"
            filterable
            placeholder="请输入关键词搜索">
            <el-option
              v-for="item in productSpecTemplateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductSpu">
import { useRouter } from "vue-router";
import {
  listProductSpu,
  getProductSpu,
  delProductSpu,
  addProductSpu,
  updateProductSpu,
} from "@/api/product/productSpu";
import { listProductSpecTemplate } from "@/api/product/productSpecTemplate";

import { listProductCategory } from "@/api/product/productCategory";
const { proxy } = getCurrentInstance();
const router = useRouter();
const { product_spu_status } = proxy.useDict("product_spu_status");

const productSpuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const productCategoryOptions = ref([]);
const productSpecTemplateOptions = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: null,
    name: null,
    subTitle: null,
    description: null,
    status: null,
  },
  rules: {
    categoryId: [
      { required: true, message: "商品分类ID不能为空", trigger: "change" },
    ],
    name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  },
  templateQueryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    status: null,
    sort: null,
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品SPU列表 */
function getList() {
  loading.value = true;
  listProductSpu(queryParams.value).then((response) => {
    productSpuList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    categoryId: null,
    name: null,
    subTitle: null,
    description: null,
    status: null,
    createdAt: null,
    updatedAt: null,
  };
  proxy.resetForm("productSpuRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getTreeselect();
  open.value = true;
  title.value = "添加商品SPU";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getTreeselect();
  const _id = row.id || ids.value;
  getProductSpu(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商品SPU";
  });
}
/** 查询商品分类下拉树结构 */
function getTreeselect() {
  listProductCategory().then((response) => {
    productCategoryOptions.value = [];
    const data = { id: 0, name: "顶级节点", children: [] };
    data.children = proxy.handleTree(response.data, "id", "parentId");
    productCategoryOptions.value.push(data);
  });
}
//查询商品规格模板下拉树结构
function getListProductSpecTemplateApi(queryParams) {
  listProductSpecTemplate(queryParams).then((response) => {
    console.log(response);
    productSpecTemplateOptions.value = response.rows.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
    // console.log(productSpecTemplateOptions.value);
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productSpuRef"].validate((valid) => {
    if (valid) {
      console.log(Number(form.value.templateId), "测试templateId的类型");
      if (form.value.id != null) {
        updateProductSpu(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        console.log(form.value, "这是表单数据");
        addProductSpu(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品SPU编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delProductSpu(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 详情按钮操作 - 跳转到详情页面 */
function handleDetail(row) {
  try {
    const id = row ? row.id : ids.value.length > 0 ? ids.value[0] : null;
    console.log("SPU ID:", id);

    if (!id) {
      proxy.$modal.msgError("无法获取SPU ID");
      return;
    }

    // 使用路径跳转
    const path = `/product/spu/detail/${id}`;
    console.log("跳转路径:", path);
    router.push(path);
  } catch (error) {
    console.error("跳转失败:", error);
    proxy.$modal.msgError("跳转详情页失败: " + error.message);
  }
}

/** 导出按钮操作 */
// function handleExport() {
//   proxy.download(
//     "product/productSpu/export",
//     {
//       ...queryParams.value,
//     },
//     `productSpu_${new Date().getTime()}.xlsx`
//   );
// }
getListProductSpecTemplateApi(data.templateQueryParams);
getList();
</script>
